package com.bw.educate.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.educate.common.tree.TreeCategory;
import com.bw.educate.entity.EduCategoryChild;
import com.bw.educate.mapper.EduCategoryChildMapper;
import com.bw.educate.service.IEduCategoryChildService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 在线教育-五组
 * @since 2020-08-12
 */
@Service
public class EduCategoryChildServiceImpl extends ServiceImpl<EduCategoryChildMapper, EduCategoryChild> implements IEduCategoryChildService {

    @Resource
    private EduCategoryChildMapper categoryChildMapper;

    @Override
    public List<TreeCategory> getTree() {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("SORT");
        List<EduCategoryChild> CategoryList = categoryChildMapper.selectList(queryWrapper);

        List<TreeCategory> list = new ArrayList<>();

        for (EduCategoryChild ca:CategoryList){
            String s = JSON.toJSONString(ca);
            TreeCategory treeCategory = JSON.parseObject(s, TreeCategory.class);
            list.add(treeCategory);
        }

        return buildTree(list);
    }

    @Override
    public void delTree(Long id) {
        //删除id专业
        categoryChildMapper.deleteById(id);
        //删除专业下的自专业
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("PARENT_ID",id);
        categoryChildMapper.delete(queryWrapper);
    }


    //把一个list转换为树
    public List<TreeCategory> buildTree(List<TreeCategory> treeCategoryList){
        List<TreeCategory> tree = new ArrayList<>();

        for (TreeCategory ca:treeCategoryList) {
            if(ca.getParentId()==0){
                tree.add(findChild(ca,treeCategoryList));
            }
        }
        return tree;
    }

    TreeCategory findChild(TreeCategory node,List<TreeCategory> treeCategoryList){
        for (TreeCategory ca:treeCategoryList) {
            if(ca.getParentId().equals(node.getId())){
                if (node.getChildren()==null){
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(findChild(ca,treeCategoryList));
            }
        }
        return node;
    }

}
